//
//  HobbiesViewController.m
//  iShop
//
//  Created by svp on 18/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HobbiesSubCategoryViewController.h"
#import "ResourceLoader.h"
#import "SelectBrandViewController.h"
//#import "PickerValueCell.h"
#import "SelectPriceRangeViewController.h"
#import "TitleTextfieldCell.h"
#import "ProductDetailViewController.h"
#import "CoreDataUtils.h"
#import "Category.h"
#import "Utils.h"

@interface HobbiesSubCategoryViewController(Private)

-(void) keyboardDidShow:(NSNotification*)notification;
-(void) keyboardDidHide:(NSNotification*)notification;

@end

//enum EHobbiesRow {
//	EBrandRow,
//	ESizeRow,
//	EPriceRow,
//	EHobbiesRowCount,
//};

@implementation HobbiesSubCategoryViewController

@synthesize tableView = _tableView;
@synthesize parentCategory = _parentCategory;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		// Custom initialization.
		_keyboardHeight = 0;
	}
	return self;
}


/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	self.title = @"Woman";
	//_sortCategories = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"Shoes",@"Skirt",@"Trousers",@"Shirt",@"Hat",nil]];
	_sortCategories = [[NSMutableArray alloc] initWithArray:[CoreDataUtils getSubCategory:_parentCategory]];
	
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditCell)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
}

-(void) endEditCell
{
	if (_keyboardHeight != 0) {
		[_tableView endEditing:YES];
		[self keyboardDidHide:nil];
	}
}

-(void) keyboardDidShow:(NSNotification*)notification
{
	NSLog(@"keyboardDidShow");
	if (_keyboardHeight != 0) {
		return;
	}
	NSDictionary* info = [notification userInfo];
	NSLog(@"notification:%@",info);
	NSLog(@"test%@",[_tableView indexPathForSelectedRow]);
	NSValue* aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	_keyboardHeight = [aValue CGRectValue].size.height;
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - _keyboardHeight);
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	
}

-(void) keyboardDidHide:(NSNotification *)notification
{
	NSLog(@"keyboardDidHide");
	if (_keyboardHeight == 0) {
		return;
	}
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height + _keyboardHeight);
	_keyboardHeight = 0;
}

-(void) viewWillAppear:(BOOL)animated
{
	NSLog(@"viewWillAppear");
	[super viewWillAppear:animated];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector (keyboardDidShow:)
												 name: UIKeyboardWillShowNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector (keyboardDidHide:)
												 name: UIKeyboardDidHideNotification object:nil];
}

-(void) viewWillDisappear:(BOOL)animated
{
	NSLog(@"viewWillDisappear");
	[super viewWillDisappear:animated];	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)dealloc {
	NSLog(@"HobbiesSubCategoryViewController dealloc");
	UpdateCategoryOrderRequest *req = [[UpdateCategoryOrderRequest alloc] init];
	NSMutableArray *categoryOrders = [[[NSMutableArray alloc] init] autorelease];
	for (Category *cat in _sortCategories) {
		NSMutableDictionary *catInfo = [[NSMutableDictionary alloc] init];
		[catInfo setObject:cat.CategoryID forKey:@"CategoryID"];
		[catInfo setObject:cat.CustomerCategoryOrder forKey:@"CategoryOrder"];
		[categoryOrders addObject:catInfo];
		[catInfo release];
	}
	NSMutableDictionary *infomation = [[[NSMutableDictionary alloc] init] autorelease];
	[infomation setObject:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
	[infomation setObject:categoryOrders forKey:@"CustomerCategoryOrders"];
	[req makeRequest:infomation];
	
	[_tableView release];
    [super dealloc];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEditing]){
		return YES;
    }
	
    return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if (section == 0) {
		return @"Sort Priority";
	}
	else {
		return @"Custom Size";
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath
{
	if (indexPath.section == 0) {
		return 70;
	}
	return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return _sortCategories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 0) {
		HobbiesSortCell* cell = (HobbiesSortCell*)[tableView dequeueReusableCellWithIdentifier:@"HobbiesSortCell"];
		if (!cell) {
			ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"HobbiesSortCell"] autorelease];
			cell = (HobbiesSortCell*)rc.resource;
			cell.delegate = self;
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
		//cell.category.text = [_sortCategories objectAtIndex:indexPath.row];
		cell.category.text = ((Category*)[_sortCategories objectAtIndex:indexPath.row]).CategoryName;
		return cell;
	}
	else {
		TitleTextfieldCell* cell = (TitleTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:@"TitleTextfieldCell"];
		if (!cell) {
			ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TitleTextfieldCell"] autorelease];
			cell = (TitleTextfieldCell*)rc.resource;
			cell.delegate = self;
			
			NSArray* sSize = [NSArray arrayWithObjects:@"S",@"S",nil];
			NSArray* mSize = [NSArray arrayWithObjects:@"M",@"M",nil];
			NSArray* lSize = [NSArray arrayWithObjects:@"L",@"L",nil];
			
			NSArray *sizePicker = [NSArray arrayWithObjects:sSize,mSize,lSize,nil];
			[cell initPickerWithArray:sizePicker];
		}
		//cell.category.text = [_sortCategories objectAtIndex:indexPath.row];
		cell.titleLabel.text = ((Category*)[_sortCategories objectAtIndex:indexPath.row]).CategoryName;
		return cell;
	}

	return nil;
}

-(void) textFieldDidBeginEditing:(UITableViewCell*)cell
{
	NSLog(@"BBB");
	_editCell = cell;
	[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:_editCell] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"didSelectRowAtIndexPath:%@",indexPath);
}

-(IBAction) savePress:(id) sender;
{
	NSLog(@"savePress");
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(IBAction) cancelPress:(id) sender;
{
	NSLog(@"cancelPress");
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}

-(void) moveUp:(HobbiesSortCell*)cell
{
	NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
	NSLog(@"move up %i",indexPath.row);
	if (indexPath.row > 0) {
		int curr = [((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder intValue];
		int new = [((Category*)[_sortCategories objectAtIndex:indexPath.row - 1]).CustomerCategoryOrder intValue];
		[_sortCategories exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row - 1];
		((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder = [NSNumber numberWithInt:curr];
		((Category*)[_sortCategories objectAtIndex:indexPath.row - 1]).CustomerCategoryOrder = [NSNumber numberWithInt:new];
		[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
		[_tableView reloadData];
	}
}

-(void) moveDown:(HobbiesSortCell*)cell
{
	NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
	NSLog(@"move Down %i",indexPath.row);
	if (indexPath.row < [_tableView numberOfRowsInSection:indexPath.section] - 1 ) {
		int curr = [((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder intValue];
		int new = [((Category*)[_sortCategories objectAtIndex:indexPath.row + 1]).CustomerCategoryOrder intValue];
		[_sortCategories exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row + 1];
		((Category*)[_sortCategories objectAtIndex:indexPath.row]).CustomerCategoryOrder = [NSNumber numberWithInt:curr];
		((Category*)[_sortCategories objectAtIndex:indexPath.row + 1]).CustomerCategoryOrder = [NSNumber numberWithInt:new];
		[((iShopAppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
		[_tableView reloadData];
	}
}


@end
